# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from field import Field
from human import Human
from computer_random import ComputerRandom
from computer_most import ComputerMost
import logging

class Table(QGraphicsObject):
    players = []
    player = False
    compas = [
                [-1, -1], [0, -1], [1, -1],
                [-1,  0],          [1,  0],
                [-1,  1], [0,  1], [1,  1]
            ]
    #compas =  [ [-1, -1] ]
    moves = dict()
    history = []
    fields = []
    playerPass = 0

    def __init__(self, parent = None, size = None, maemo = False):
        QGraphicsObject.__init__(self, parent)

        #if geometry.height() > geometry.width(): self.size = geometry.width()
        #else: self.size = geometry.height()
        #self.scene.setSceneRect(0, 0, self.size, self.size)
        self.size = size

        size = ((self.size)/8) - 3

        for i in range(0, 8):
            row = []
            for j in range(0, 8):
                field = Field(self, size = size, x = i, y = j, maemo = maemo)
                #field.setParentItem(self)
                row.append(field)
            self.fields.append(row)

        player = Human(self)
        self.players.append(player)

        computer = ComputerMost(self)
        self.players.append(computer)

        self.fields[3][3].starting(True)
        self.fields[4][3].starting(False)
        self.fields[3][4].starting(False)
        self.fields[4][4].starting(True)

        self.newGame()
        #self.connect(self.fields[0][0] , SIGNAL('clicked'), self.makeMove)

    def paint(self, painter, option, widget):
        pass

    def boundingRect(self):
        return QRectF(0, 0, self.size, self.size)

    def newGame(self):
        #print 'new game'
        for i in range(0, 8):
            for j in range(0, 8):
                self.fields[i][j].reset()
        self.player = False
        self.players[int(self.player)].activate()
        self.emit(SIGNAL('setScores'), [2, 2])
        self.hitstory = []
        self.playerPass = 0
        self._calculatePossibleMoves()
        #print self.moves

    def _calculatePossibleMoves(self):
        self.moves = dict()
        for x in range(0, 8):
            for y in range(0, 8):
                if self.fields[x][y].get() != self.player:
                    continue
                fields = []
                for dx, dy in self.compas:
                    if (not (0 <= (x + dx) < 8) or not (0 <= (y + dy) < 8)):
                        continue
                    #print '1check field %s - %s' % (x, y)
                    #print '1direction %s - %s' % (dx, dy)
                    turnFields = self._checkFields(x + dx, y + dy, dx, dy)
                    #print 'found %s' % turnFields
                    if isinstance(turnFields, list):
                        #fields.extend(turnFields)
                        turnFields.reverse()
                        self.fields[turnFields[0][0]][turnFields[0][1]].setPossible(True)
                        try: self.moves['%s-%s' % (turnFields[0][0], turnFields[0][1])][1].extend(turnFields[1:])
                        except: self.moves.update({'%s-%s' % (turnFields[0][0], turnFields[0][1]) : [[turnFields[0][0], turnFields[0][1]], turnFields[1:]]})

                #print self.moves

    def _checkFields(self, x, y, dx, dy, enemy = False):
        #print '1111check field %s - %s' % (x, y)
        if not 0 <= x <= 7 or not 0 <= y <= 7: return False
        #print 'check field %s - %s' % (x, y)
        #print 'direction %s - %s' % (dx, dy)
        #print 'player %s' % self.fields[x][y].get()
        if self.fields[x][y].get() == self.player: return False
        if not self.fields[x][y].isSet():
            if enemy: return [[x, y]]
            else: return False
        #print 'check field %s - %s' % (x, y)
        #print 'direction %s - %s' % (dx, dy)
        #print 'player %s' % self.fields[x][y].get()
        turnFields = self._checkFields(x + dx, y + dy, dx, dy, True)
        #print 'turnFields %s' % turnFields
        if not turnFields: return False
        if turnFields == True: return [[x, y]]
        fields = [[x, y]]
        fields.extend(turnFields)
        #print 'fields %s' % fields
        return fields

    def pick(self, x, y):
        #print self.moves
        #print 'picked %s - %s' % (x, y)
        if self.fields[x][y].isSet(): return False
        if not '%s-%s' % (x, y) in self.moves: return False
        #f = open('moves.txt', 'a')
        #f.write('%s' % self.moves['%s-%s' % (x, y)])
        #f.write('\n')
        #f.close()
        #self.history.append(self.moves['%s-%s' % (x, y)])
        self.history.append([self.player, x, y])
        self.fields[x][y].set(self.player)
        for tx, ty in self.moves['%s-%s' % (x, y)][1]:
            self.fields[tx][ty].set(self.player)
        self.nextPlayer()
        #self.update()
        return True

    def nextPlayer(self):
        #print 'next player'
        scores = [0, 0]
        for i in range(0, 8):
            for j in range(0, 8):
                self.fields[i][j].setPossible(False)
                if self.fields[i][j].isSet():
                    scores[int(self.fields[i][j].get())] += 1
        self.emit(SIGNAL('setScores'), scores)
        if ((scores[0] + scores[1]) == (8*8)) or (scores[0] == 0) or (scores[1] == 0):
            self.emit(SIGNAL('gameOver'), scores)
            return False
        self.players[int(self.player)].deactivate()
        self.player = True if not self.player else False
        self._calculatePossibleMoves()
        #print self.moves
        if not self.moves:
            if self.playerPass >= 2:
                self.emit(SIGNAL('gameOver'), scores)
                return False
            self.playerPass += 1
            if not self.nextPlayer():
                return False
        self.playerPass = 0
        self.players[int(self.player)].activate()

    def getPosibleMoves(self):
        return self.moves

    def saveHistory(self, file):
        import os
        dir = os.path.dirname(file)
        if not os.path.exists(dir):
            os.makedirs(dir)

        f = open(file, 'w')
        f.write(str(self.history))
        f.close()
        return True

    #def makeMove(self):
    #    self.players[int(self.player)].activate()
